<template>
    <view class="layout">
        <view class="finish">
			<view class="countdown">
				学习倒计时：{{ countdownStore.formattedTime }}
			</view>
            <view class="finishBtn" @click="onFinish">
                结束本轮
            </view>
        </view>
        <view class="content">
            <view v-for="item in paginatedData" :key="item.number">
                <view :class="[item.number == selectedId ? 'active-item' : 'item']"
                    @click="onClickItem(item.number, item.word)">
					<view class="leftText">
						<text>{{item.word}}</text>
					</view>
					<view class="rightText">
						<text v-if="selectedId === item.number && showTranslation">{{item.meaning}}</text>
					</view>
                    <!-- <text class="leftText">{{item.word}}</text> -->
                    <!-- <text class="rightText" v-if="selectedId === item.number && showTranslation">{{item.meaning}}</text> -->
                </view>
            </view>
        </view>
        <view class="bottom">
            <view class="left">
                <uni-icons type="arrow-left" size="30" :color="currentPage == 1 ? 'transparent' : 'black'"
                    @click="prevPage"></uni-icons>
                <text>{{currentPage}} / {{totalPages}}</text>
                <uni-icons type="arrow-right" size="30" :color="currentPage == totalPages ? 'transparent' : 'black'"
                    @click="nextPage"></uni-icons>
            </view>
            <view class="right">
                <uni-icons custom-prefix="iconfont" type="icon-jianqie" size="30" color="#18BB7C" @click="goToCutPaperBox"></uni-icons>
                <uni-icons type="sound-filled" size="30" color="black"></uni-icons>
            </view>
        </view>
    </view>
</template>

<script setup>
    import {
        ref,
        computed
    } from "vue";
    import {
        onLoad,
		onReady,
        onUnload, onShow, onHide
    } from '@dcloudio/uni-app';
	import { useUserInfoStore } from '../../store';	
	import { useStudyInfoStore } from '../../store';
	import { useCountdownStore } from '../../store';
	
	//获得store实例对象
	const userInfoStore = useUserInfoStore()
	//获得store实例对象
	const studyInfoStore = useStudyInfoStore()
	
	const countdownStore = useCountdownStore()

    let wordsList = ref([]);

    //选中的单词id
    let selectedId = ref(-1);
    //是否显示中文翻译
    let showTranslation = ref(false);

    //当前页数
    let currentPage = ref(1);
    let pageSize = ref(5);
	
	let inThisPage = true;
	
    onLoad(async () => {
		if(studyInfoStore.studyMode === 0){
			//从studyInfoStore中获取选择单词列表
			let arr = studyInfoStore.studyWordsList;
			let wordBank = uni.getStorageSync(studyInfoStore.wordBankId)
			//根据number从词库中赛选单词
			arr.forEach((item) => {
			    wordsList.value.push(wordBank.find(word => word.number === item))
			})
			
			//正则表达式解析
			wordsList.value.map(item => {
				if(item.meaning.includes(".")){
					let regex = /(?<=\.{1})[^\.]+?(?=[,，；]|$)/g;
					let match = item.meaning.match(regex);
					item.meaning = match.join()
				}
			})
			
			// 监听事件
			uni.$on('nextPage', () => {
			    nextPage();
			})
		} else if(studyInfoStore.studyMode === 1) {
			let wordBank = uni.getStorageSync(studyInfoStore.wordBankId)
			
			let res = undefined
			/// mark01
			if(userInfoStore.userInfo.role === 0) {
				res = await uniCloud.callFunction({
					name: "getStudyedWords",
					data: {
						relateUuid: userInfoStore.userInfo.uuid,
						wordBankId: studyInfoStore.wordBankId
					}
				})
			} else if(userInfoStore.userInfo.role === 1) {
				res = await uniCloud.callFunction({
					name: "getStudyedWords",
					data: {
						relateUuid: userInfoStore.selectedStudentInfo.uuid,
						wordBankId: studyInfoStore.wordBankId
					}
				})
			}

			console.log(res.result)
			const fliterWordList = res.result.filter(item => (item.studyedNum < 7 || item.forget === true))
			
			//提取word字段
			const tempArr = new Set(fliterWordList.map(item => item.word));
			
			const resultArr = wordBank.filter(item => tempArr.has(item.word))
			
			wordsList.value = getRandomItems(resultArr, 20);
			
			//正则表达式解析
			wordsList.value.map(item => {
				if(item.meaning.includes(".")){
					let regex = /(?<=\.{1})[^\.]+?(?=[,，；]|$)/g;
					let match = item.meaning.match(regex);
					item.meaning = match.join()
				}
			})
			
			let unknownWordList = [];
			unknownWordList = wordsList.value.map(item => {
				return item.number
			})
			studyInfoStore.setStudyWordsList(unknownWordList);
			
			countdownStore.startCountdown(900);
			// countdownStore.startCountdown(10);
		}
        
    })
	
	onShow(() => {
		console.log("显示")
		inThisPage = true;
	})
	
	onHide(() => {
		console.log("隐藏")
		inThisPage = false;
	})

	onReady(() => {
		// 监听倒计时结束事件
		uni.$on('countdownFinished', () => {
		  uni.showToast({
		    title: '倒计时结束',
		    icon: 'none'
		  })
		  if(studyInfoStore.studyMode === 0){
		  	uni.$emit('finish');
		  	uni.navigateBack();
		  } else if(studyInfoStore.studyMode === 1) {
		  	// uni.navigateTo({
		  	// 	url: "/pages/detection/detection"
		  	// })
			if(inThisPage){
				uni.redirectTo({
					url: "/pages/detection/detection"
				})
			} else {
				uni.navigateBack(
					{
						success() {
							setTimeout(() => {
								uni.redirectTo({
									url: "/pages/detection/detection"
								})
							}, 300);
						}
					}
				)
			}


		  }
		})
	})

    onUnload(() => {
        // 移除监听事件
        uni.$off('nextPage');
		uni.$off('countdownFinished');
    })
	
	// 随机抽取数据的方法
	function getRandomItems(array, count) {
	    // 首先复制数组，避免修改原数组
	    let copiedArray = array.slice();
	
	    // 用于存储随机抽取的数据
	    let result = [];
	
	    // 循环抽取指定数量的数据
	    for (let i = 0; i < count; i++) {
	        // 如果数组为空，跳出循环
	        if (copiedArray.length === 0) break;
	
	        // 随机生成一个索引
	        let randomIndex = Math.floor(Math.random() * copiedArray.length);
	
	        // 将随机选中的数据添加到结果数组中
	        result.push(copiedArray[randomIndex]);
	
	        // 从复制的数组中移除已经选中的数据
	        copiedArray.splice(randomIndex, 1);
	    }
	
	    return result;
	}

    function onClickItem(number, word) {
        if (selectedId.value === number) {
            showTranslation.value = !showTranslation.value;
        } else {
            showTranslation.value = false;
        }
        selectedId.value = number;
		
		// let tempWord = word.trim()
		let tempWord = word
		if(tempWord.includes('/')) {
			let regex = /(\b[A-Za-z.]+)\s*(?=\/)/g;
			tempWord = tempWord.match(regex)[0];
		} else if(tempWord.includes('(')) {
			let regex = /(\b[A-Za-z.]+)\s*(?=\()/g;
			tempWord = tempWord.match(regex)[0];
		}

		tempWord = tempWord.replace(/-+/g, ' ').trim()
		
        voiceplay(tempWord);
    }

    //点击本轮结束
    function onFinish() {
		if(studyInfoStore.studyMode === 0){
			uni.$emit('finish');
			uni.navigateBack();
		} else if(studyInfoStore.studyMode === 1) {
			// uni.navigateTo({
			// 	url: "/pages/detection/detection"
			// })
			uni.redirectTo({
				url: "/pages/detection/detection"
			})
		}

    }

    //显示或隐藏中文翻译
    function showOrHideTranslation() {

    }

    // 计算当前页的数据
    const paginatedData = computed(() => {
        const start = (currentPage.value - 1) * pageSize.value;
        const end = start + pageSize.value;
        return wordsList.value.slice(start, end);
    });

    // 计算总页数
    const totalPages = computed(() => {
        return Math.ceil(wordsList.value.length / pageSize.value);
    });

    // 上一页
    function prevPage() {
        if (currentPage.value > 1) {
            currentPage.value--;
            selectedId.value = -1;
            showTranslation.value = false;
        }
    }

    // 下一页
    function nextPage() {
        if (currentPage.value < totalPages.value) {
            currentPage.value++;
            selectedId.value = -1;
            showTranslation.value = false;
        }
    }

    //跳转剪纸盒页面
    function goToCutPaperBox() {
        //是否是第一页 尾页 用于判断弹窗选项
        let isFirst = false;
        let isEnd = false;
        if (currentPage.value === 1) {
            isFirst = true;
        }
        if (currentPage.value === totalPages.value) {
            isEnd = true;
        }
        uni.navigateTo({
            url: `/pages/cut-paper-box/cut-paper-box?page=${currentPage.value}&isFirst=${JSON.stringify(isFirst)}&isEnd=${JSON.stringify(isEnd)}`
        })
    }

    //音频播放 type=0是英音，1是美音
    function voiceplay(key) {
        uni.showLoading({
            title: '加载中',
        })
        const innerAudioContext = uni.createInnerAudioContext();
        innerAudioContext.autoplay = true;
        // http://dict.youdao.com/dictvoice?type=0&audio=' + key; key 是需要发音的单词，链接就是有道词典的接口链接，返回就是一个音频，直接可以播放，可以直接在游览器打开。
        innerAudioContext.src = 'http://dict.youdao.com/dictvoice?type=0&audio=' + key;
        innerAudioContext.onPlay(() => {
            console.log('开始播放');
            uni.hideLoading();
        });
        innerAudioContext.onError((res) => {
            console.log(res.errMsg);
            console.log(res.errCode);
            uni.hideLoading();
        });
        uni.hideLoading();
    }
</script>

<style lang="scss" scoped>
    .layout {
        background-color: #F5F5F5;
        height: 100vh;
        position: relative;
        .finish {
            display: flex;
            justify-content: space-between;
			align-items: center;
			.countdown{
				font-size: 50rpx;
				color: #18BB7C;
			}
            .finishBtn {
                margin-right: 20rpx;
                margin-top: 20rpx;
                background-color: #18BB7C;
                padding: 20rpx 40rpx;
                border-radius: 50rpx;
                color: white;
            }
        }

        .content {
            padding: 20rpx;
            overflow: hidden;

            .active-item {
                margin: 20rpx 0;
                padding: 20rpx;
                font-size: 24px;
                background-color: white;
                border: 1px solid green;
                display: flex;
                flex-direction: row;
                justify-content: space-between;
				
				.leftText{
					flex: 3;
					word-break: break-all;
				}
				.rightText{
					flex: 1;
					text-align: center;
				}
            }

            .item {
                margin: 20rpx 0;
                padding: 20rpx;
                font-size: 24px;
                background-color: white;
                display: flex;
                flex-direction: row;
                justify-content: space-between;
				
				.leftText{
					flex: 3;
					word-break: break-all;
				}
				.rightText{
					flex: 1;
					text-align: center;
				}
            }
        }

        .bottom {
            background-color: white;
            padding: 20rpx 40rpx 150rpx 40rpx;
            position: absolute;
            width: 100%;
            box-sizing: border-box;
            bottom: 0;
            display: flex;
            flex-direction: row;
            justify-content: space-between;

            .left {
                display: flex;
                gap: 20rpx;
                align-items: center;

                text {
                    font-size: 20px;
                }
            }

            .right {
                display: flex;
                gap: 20rpx;
            }
        }
    }
</style>